package com.agent.web.filehandling;

import com.agent.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;

/**
 * Created by hg on 2019/6/22.
 */
@Controller
@Slf4j
@RequestMapping("/pic")
public class PicController {

    @RequestMapping("/getPic")
    public void getPic(HttpServletRequest request, HttpServletResponse response,String fileId) throws IOException {
        if(CommonUtils.isEmptyOrNull(fileId)){
            return;
        }
        File file = new File(URLDecoder.decode(fileId,"UTF-8"));

        OutputStream fos = null;
        if(file.exists()){
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            response.reset();
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("image/jpeg");
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

        }
    }
}
